const { createAddres, findAllAddr, updateAddr, removeAddr, setDefaultAddr } = require('../service/address.service')
const { addresAddError } = require("../constant/err.type")

class AddressController {
    async create(ctx, next) {
        const { consignee, address, phone } = ctx.request.body
        const user_id = ctx.state.user.id
        // 操作数据库 
        try {
            const res = await createAddres({ user_id, consignee, address, phone })
            // 返回客户端
            ctx.body = {
                code: 0,
                message: "添加地址成功",
                result: res
            }
        } catch (err) {
            console.error(err)
            ctx.app.emit('error', addresAddError, ctx)
        }
    }
    async findAll(ctx, next) {
        const user_id = ctx.state.user.id
        const res = await findAllAddr(user_id)
        // 返回客户端
        ctx.body = {
            code: 0,
            message: "获取地址列表成功",
            result: res
        }
    }
    async update(ctx, next) {
        const addr_id = ctx.request.params.id
        const { consignee, address, phone } = ctx.request.body

        const res = await updateAddr(addr_id, ctx.request.body)
        // 返回客户端
        ctx.body = {
            code: 0,
            message: "更新地址成功",
            result: res[0]
        }
    }
    async remove(ctx, next) {
        const addr_id = ctx.request.params.id
        const res = await removeAddr(addr_id)
        ctx.body = {
            code: 0,
            message: "删除地址成功",
            result: res
        }
    }
    // 排他思想 mysql 触发器
    async setDefault(ctx, next) {
        // 排他思想
        const addr_id = ctx.request.params.id
        const user_id = ctx.state.user.id

        const res = await setDefaultAddr(addr_id, user_id)

        ctx.body = {
            code: 0,
            message: "设置默认地址成功",
            result: res[0]
        }
    }
}
module.exports = new AddressController()